package com.parkreport.login.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.common.base.BaseServlet;
import com.common.util.StringUtil;
import com.parkreport.admin.user.service.UserService;
import com.parkreport.login.service.LoginService;
import com.parkreport.vo.UsersVO;

public class LoginServlet extends BaseServlet {
	LoginService service = new LoginService();
	UserService userService = new UserService();
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		this.req=req;
		this.res=res;
		
		String method = req.getParameter("method");
		if("login".equalsIgnoreCase(method)){
			login();
		}else if("logout".equalsIgnoreCase(method)){
			logout();
		}else if("editpassword".equalsIgnoreCase(method)){
			logout();
		}else{
			login();
		}
	}

	private void editPass(){
		String id = req.getParameter("id");
		/*UsersVO userVO = userService.get(id);
		req.getSession().setAttribute("password", userVO.getPassword());*/
	}
	private void savePass(){
		String id = req.getParameter("id");
		String oldpassword = req.getParameter("oldpassword");
		String password = req.getParameter("password");
		UsersVO userVO = userService.get(id);
		
		if(!StringUtil.isBlank(oldpassword)&&oldpassword.equals(userVO.getPassword())){
			userService.updatPass(id, password);
		}
	}
	private void login() throws ServletException, IOException{
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		String randcode = req.getParameter("randcode");
		String rand = (String) req.getSession().getAttribute("rand");
		if(rand!=null&&rand.equals(randcode)){
			UsersVO vo = new UsersVO();
			vo.setUsername(username);
			vo.setPassword(password);
			
			boolean isLogin = service.login(vo);
			if(isLogin){
				req.getSession().setAttribute("users", vo);
				req.getRequestDispatcher("./index.jsp").forward(req, res);
			}else{
				req.setAttribute("msg", "用户名密码错误！");
				req.getRequestDispatcher("./login.jsp").forward(req, res);
			}
		}else{
			req.setAttribute("msg", "验证码出错！");
			req.getRequestDispatcher("./login.jsp").forward(req, res);
		}
	}
	
	private void logout() throws IOException{
		req.getSession().removeAttribute("users");
		res.sendRedirect("./login.jsp");
	}
	
}
